package drds.global_transaction.global_transaction_manager.dubbo.impl;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import drds.global_transaction.api.global_transaction_id_context.GlobalTransactionIdContexts;
import drds.global_transaction.spring.annotation.GlobalTransaction;
import drds.global_transaction.global_transaction_manager.dubbo.BusinessService;
import drds.global_transaction.global_transaction_manager.dubbo.OrderService;
import drds.global_transaction.global_transaction_manager.dubbo.StorageService;
import lombok.extern.slf4j.Slf4j;

/**
 * Please map$clientPortToRpcContextMap the follow VM arguments:
 *
 * <pre>
 *     -Djava.net.preferIPv4Stack=true
 * </pre>
 */
@Slf4j
public class BusinessServiceImpl implements BusinessService
{

	private StorageService storageService;
	private OrderService orderService;

	public static void main(String[] args)
	{
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] { "dubbo-business.xml" });
		final BusinessService businessService = (BusinessService) applicationContext.getBean("business");

		log.info("Main business globalTransactionBegin ... globalTransactionIdWithAddressAndPort: " + GlobalTransactionIdContexts.getGlobalTransactionIdWithAddressAndPort());
		businessService.purchase("U100001", "C00321", 2);
		log.info("Main business end ... globalTransactionIdWithAddressAndPort: " + GlobalTransactionIdContexts.getGlobalTransactionIdWithAddressAndPort());
	}

	@Override
	@GlobalTransaction(timeoutMilliseconds = 300000, name = "dubbo-demo-tx")
	public void purchase(String userId, String commodityCode, int orderCount)
	{
		storageService.deduct(commodityCode, orderCount);
		orderService.create(userId, commodityCode, orderCount);

	}

	public void setStorageService(StorageService storageService)
	{
		this.storageService = storageService;
	}

	public void setOrderService(OrderService orderService)
	{
		this.orderService = orderService;
	}
}
